<template>
    <div>
        <el-upload
            ref="upload"
            :action="uploadImgUrl"
            :on-remove="handleRemove"
            :limit="1"
            :on-success="handleSuccess"
            :file-list="fileList"
            :auto-upload="true"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload">
            <el-button slot="trigger" type="primary" size="small" >上传图片</el-button>
            <div slot="tip" class="el-upload__tip" style="margin-top: 10px;">只能上传 jpg/jpeg/png/gif 文件，且不超过10M</div>
        </el-upload>
    </div>
</template>

<script>
export default {
    data() {
        return {
            uploadImgUrl: global.baseurl + '/api/upload/img',
            fileList: [],
        }
    },
    props: ['rule'],
    methods: {
        handleExceed(files, fileList) {
            this.$message.error(`最多上传一张图片`);
        },
        handleRemove(file, fileList) {
            let that = this;
            //从服务器也删除此文件
            that.$axios.delete('/api/delete/file', {
                data: {
                    path: that.fileList[fileList.length]
                }
            })
            that.fileList.splice(fileList.length, 1)
            let data = {
                fileList: this.fileList,
                rule: this.rule
            }
            this.$emit('upChange', data)
        },
        handleSuccess(res, file, fileList) {
            this.fileList.push(file)
            let data = {
                fileList: this.fileList,
                rule: this.rule
            }
            this.$emit('upChange', data)
        },
        beforeUpload(file) {
            let that = this;
            let canUpload = true; //是否能够上传（布尔值）
            let type = file.name.substring(file.name.lastIndexOf('.') + 1);
            //不区分大小写
            if (!/jpg|jpeg|png|gif/i.test(type)) {
                that.$message({
                    message: "文件格式只能是jpg/jpeg/png/gif",
                    type: 'warning'
                });
                canUpload = false;
            }
            let size = file.size / 1024 / 1024;
            if (size > 10) {
                that.$message({
                    message: "文件大小不能超过10M",
                    type: 'warning'
                });
                canUpload = false
            }
            return canUpload
        },
    }
}
</script>